<script setup>
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Location, Clock, Search } from '@element-plus/icons-vue'
import { listRoom, getRoom } from '@/api/room'
import { listSeat, getSeat } from '@/api/seat'
import { listReservation, getReservation, addReservation, updateReservation } from '@/api/reservation'
import { baseURL } from '@/utils/request.js'
import { useUserStore } from '@/stores'
const userStore = useUserStore()


const loading = ref(false)      // 加载
const roomList = ref([])        // 自习室列表
const searchKeyword = ref('')   // 自习室搜索
const ResetBtnShow = ref(false) // 重置按钮
function getList() {
  loading.value = true
  roomList.value = []
  listRoom({ name: searchKeyword.value }).then(res => {
    roomList.value = res.data.rows
    loading.value = false
  })
}
getList()
function SearchBtn() {
  if (searchKeyword.value == '') {
    ElMessage.error('请输入自习室名称')
    return
  }
  loading.value = true
  ResetBtnShow.value = true
  getList()
}
function ResetBtn() {
  loading.value = true
  searchKeyword.value = ''
  ResetBtnShow.value = false
  getList()
}


const loading2 = ref(false) // 加载
const roomShow = ref(false) // 自习室详情
const roomData = ref({})    // 自习室数据
const seatList = ref([])    // 自习室座位
const selectedSeat = ref()  // 选中的座位
function selectSeat(room) {
  // 自习室关闭
  if (room.status == '关闭') {
    ElMessage.error('自习室已关闭，请选择其他自习室')
    return
  }
  // 自习室未到开放时间
  if (room.openTime > new Date().toLocaleTimeString() || room.closeTime < new Date().toLocaleTimeString()) {
    ElMessage.error('自习室未到开放时间')
    return
  }
  loading2.value = true
  roomShow.value = true
  selectedSeat.value = null
  reservationData.value = {
    userId: null,
    seatId: null,
    status: null,
    reservationStatus: null,
    reservationInTime: null,
    reservationOutTime: null,
  }
  const queryParams = {
    pageNum: 1,
    pageSize: 10,
    roomId: null,
    reservationStatus: null
  }
  queryParams.roomId = room.id
  getRoom(room.id).then(res => { roomData.value = res.data.data })
  listSeat(queryParams).then(res => {
    queryParams.pageSize = res.data.total
    listSeat(queryParams).then(res => {
      seatList.value = res.data.rows
      loading2.value = false
    })
  })
  // 预约记录
  listReservation({ userId: userStore.user.userId }).then(res => {
    if (res.data.total) {
      if (res.data.rows[0].reservationStatus == '已预约' || res.data.rows[0].reservationStatus == '使用中') {
        selectedSeat.value = res.data.rows[0].seatId
      }
    }
  })
}

// 根据自习室布局生成座位网格
const seatGrid = computed(() => {
  const rows = roomData.value.rowsCount // 行数
  const cols = roomData.value.colsCount // 列数
  // 创建一个空座位网格，用于填充
  const grid = []
  // 生成所有位置（包括空位）
  for (let rowNum = 1; rowNum <= rows; rowNum++) {
    for (let colNum = 1; colNum <= cols; colNum++) {
      // 默认创建空位
      grid.push({
        roomId: roomData.value.id,
        rowNum,
        colNum,
        status: null,
      })
    }
  }
  // 获取所有预约记录
  listReservation().then(res => {
    const allReservations = res.data.rows
    // 筛选出状态为"已预约"或"使用中"的记录
    const activeReservations = allReservations.filter(r => (r.reservationStatus === '已预约' || r.reservationStatus === '使用中') && r.userId !== userStore.user.userId) // 排除当前用户的预约记录
    // 更新对应座位的状态
    seatList.value.forEach(seat => {
      const matchingReservation = activeReservations.find(r => r.seatId === seat.id);
      if (matchingReservation) {
        seat.status = matchingReservation.reservationStatus; // 设置为'已预约'或'使用中'
      }
      // 座位编号 = (行号 - 1) × 列数 + 列号
      const index = (seat.rowNum - 1) * cols + seat.colNum - 1
      if (index >= 0 && index < grid.length) {
        grid[index] = seat
      }
    });
  })

  // 用实际座位数据替换空位
  seatList.value.forEach(seat => {
    // 座位编号 = (行号 - 1) × 列数 + 列号
    const index = (seat.rowNum - 1) * cols + seat.colNum - 1
    if (index >= 0 && index < grid.length) {
      grid[index] = seat
    }
  })
  return grid
})
// 获取座位状态样式
function getSeatClass(seat) {
  let baseClass = ''
  if (seat.status === 0) baseClass = 'seat-normal';
  if (seat.status === 1) baseClass = 'seat-fault';
  if (seat.status === null) baseClass = 'seat-empty';
  if (seat.status == '已预约') baseClass = 'seat-reserved';
  if (seat.status == '使用中') baseClass = 'seat-using';
  // 添加选中状态样式
  if (selectedSeat.value === seat.id) {
    baseClass += ' seat-selected'
  }
  return baseClass
}
// 根据自习室布局生成座位网格
const gridStyle = computed(() => {
  if (!roomData.value) return {}
  return {
    gridTemplateColumns: `repeat(${roomData.value.colsCount}, 1fr)`
  }
})
// 自动适配座位样式大小
const seatSize = computed(() => {
  if (!roomData.value) return {}
  if (roomData.value.colsCount == 7) {
    return {
      width: '30px',
      height: '30px',
    }
  }
  if (roomData.value.colsCount == 8) {
    return {
      width: '26px',
      height: '26px',
    }
  }
  if (roomData.value.colsCount == 9) {
    return {
      width: '22px',
      height: '22px',
    }
  }
  if (roomData.value.colsCount == 10) {
    return {
      width: '20px',
      height: '20px',
    }
  }
})

// 预约
const reservationData = ref({
  userId: null,
  seatId: null,
  status: null,
  reservationStatus: null,
  reservationInTime: null,
  reservationOutTime: null,
})
function reservation(seat) {
  if (seat.status === '使用中') {
    ElMessage.error('该座位正在使用中，不可预约')
  }
  if (seat.status === '已预约') {
    ElMessage.error('该座位已预约，请勿重复预约')
  }
  if (seat.status === 1) {
    ElMessage.error('该座位已故障，不可预约')
  }
  // 预约记录
  listReservation({ userId: userStore.user.userId }).then(res => {
    if (res.data.total) {
      if (selectedSeat.value == seat.id) {
        ElMessage.success('你已预约此座位')
        return
      }
      if (res.data.rows[0].reservationStatus == '已预约' && seat.status == 0 || res.data.rows[0].reservationStatus == '使用中') {
        ElMessage.error('你已预约，不可重复预约')
        return
      }
    }
    if (seat.status === 0) {
      selectedSeat.value = seat.id
      const nowIn = new Date()
      const nowOut = new Date()
      nowIn.setHours(nowIn.getHours() + 8)
      nowOut.setHours(nowOut.getHours() + 10)
      reservationData.value = {
        userId: userStore.user.userId,
        seatId: seat.id,
        status: '正常',
        reservationStatus: '已预约',
        // 预约时间（获取当前时间）
        reservationInTime: nowIn.toISOString().replace('T', ' ').split('.')[0],
        reservationOutTime: nowOut.toISOString().replace('T', ' ').split('.')[0],
      }
    }
  })
}
function reservationBtn() {
  addReservation(reservationData.value).then(res => {
    if (res.data.code === 200) {
      roomShow.value = false
      ElMessage.success('预约成功')
    }
  })
}
</script>

<template>
  <div class="user">
    <el-container>
      <el-header>预约</el-header>
      <el-main>
        <el-input v-model="searchKeyword" placeholder="搜索自习室" clearable>
          <template #append>
            <el-button :icon="Search" @click="SearchBtn" />
          </template>
        </el-input>
        <el-button v-if="ResetBtnShow" @click="ResetBtn" style="width: 100%;">重置</el-button>

        <!-- 自习室列表 -->
        <div class="room-list" v-loading="loading">
          <div class="room-card" v-for="item in roomList" :key="item.id" @click="selectSeat(item)">
            <el-image :src="baseURL + item.image" />
            <div class="left">
              <h4>{{ item.name }}</h4>
              <p>
                <el-icon>
                  <Location />
                </el-icon>
                {{ item.location }}
              </p>
              <p>
                <el-icon>
                  <Clock />
                </el-icon>
                {{ item.openTime }} ~ {{ item.closeTime }}
              </p>
            </div>
            <div class="right">
              <p>
                <el-tag type="success" v-if="item.status == '开放'">状态：{{ item.status }}</el-tag>
                <el-tag type="danger" v-else>状态：{{ item.status }}</el-tag>
              </p>
              <p><el-tag>布局：{{ item.rowsCount }}行 × {{ item.colsCount }}列</el-tag></p>
            </div>
          </div>
          <el-empty v-if="roomList.length == 0" description="没有搜索到此自习室！" />
        </div>
      </el-main>

      <!-- 选择座位 -->
      <el-dialog v-model="roomShow" title="选择座位" width="98%">
        <div class="room-info">
          <h4>{{ roomData.name }}</h4>
          <p>
            <el-icon>
              <Location />
            </el-icon>
            {{ roomData.location }}
          </p>
          <p>
            <el-icon>
              <Clock />
            </el-icon>
            {{ roomData.openTime }} ~ {{ roomData.closeTime }}
          </p>
        </div>
        <div class="legend">
          <div class="legend-item">
            <div class="legend-color" style="background-color: #409EFF;"></div>
            <span>空闲</span>
          </div>
          <div class="legend-item">
            <div class="legend-color" style="background-color: #E6A23C;"></div>
            <span>已预约</span>
          </div>
          <div class="legend-item">
            <div class="legend-color" style="background-color: #909399;"></div>
            <span>使用中</span>
          </div>
          <div class="legend-item">
            <div class="legend-color" style="background-color: #F56C6C;"></div>
            <span>故障</span>
          </div>
        </div>
        <div class="seat-map-container" v-loading="loading2">
          <div class="seat-map" :style="gridStyle">
            <div v-for="seat in seatGrid" :key="seat.id" class="seat" :class="getSeatClass(seat)" :style="seatSize"
              @click="reservation(seat)">
              {{ seat.seatNum }}
              <span v-if="seat.id === selectedSeat">已选择</span>
              <span v-else-if="seat.status === 0">空闲</span>
              <span v-if="seat.status === 1">故障</span>
              <span v-if="seat.status == '已预约'">已预约</span>
              <span v-if="seat.status == '使用中'">使用中</span>
            </div>
          </div>
        </div>
        <template #footer>
          <el-button @click="roomShow = false">取消</el-button>
          <el-button type="primary" @click="reservationBtn" :disabled="!reservationData.userId">预约</el-button>
        </template>
      </el-dialog>
    </el-container>
  </div>
</template>

<style lang="scss" scoped>
.user {
  height: 100%;

  .el-container {
    height: 100%;

    .el-header {
      display: flex;
      align-items: center;
      justify-content: center;
      height: 40px;
      color: #555555;
      font-size: 16px;
      background-color: #ffffff;
    }

    .el-main {
      padding: 5px;

      .room-list {
        margin: 10px 0;
        display: flex;
        flex-direction: column;
        gap: 10px;

        .room-card {
          padding: 10px;
          background-color: #ffffff;
          border-radius: 8px;
          box-shadow: 0 2px 6px #00000020;

          .el-image {
            width: 100%;
            border-radius: 8px;
          }

          .left {
            float: left;
            width: 50%;

            h4 {
              padding: 4px 0;
              color: #555555;
              font-size: 16px;
            }

            p {
              display: flex;
              align-items: center;
              gap: 2px;
              padding: 4px 0;
              color: #555555;
              font-size: 12px;
            }
          }

          .right {
            float: right;
            text-align: right;
            width: 50%;

            .el-tag {
              margin: 4px 0;
            }
          }
        }
      }
    }

    .room-info {
      padding: 10px;
      background-color: #f8f9fa;
      border-radius: 8px;

      h4 {
        font-size: 16px;
        text-align: center;
      }

      p {
        display: flex;
        align-items: center;
        gap: 2px;
        padding: 4px 0;
        color: #555555;
        font-size: 12px;
      }
    }

    // 座位图例
    .legend {
      display: flex;
      justify-content: space-around;
      margin: 20px auto;
      max-width: 400px;

      .legend-item {
        display: flex;
        align-items: center;
        gap: 5px;
        font-size: 0.9rem;
      }

      .legend-color {
        width: 16px;
        height: 16px;
        border-radius: 4px;
      }
    }

    // 座位地图
    .seat-map-container {
      display: flex;
      align-items: center;
      justify-content: center;
      margin: 20px auto;
      max-width: 600px;
      max-height: 600px;
      overflow: auto;

      .seat-map {
        display: grid;
        gap: 10px;
        padding: 15px;
        background: #f7fafc;
        border-radius: 8px;
        box-shadow: inset 0 0 10px rgba(0, 0, 0, 0.05);
        justify-content: center;
      }

      .seat {
        display: flex;
        align-items: center;
        justify-content: center;
        flex-direction: column;
        width: 40px;
        height: 40px;
        font-size: 0.8rem;
        font-weight: bold;
        border-radius: 6px;
        cursor: pointer;
        transition: all 0.2s;
        box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);

        span {
          font-size: 0.6rem;
          font-weight: normal;
        }
      }

      .seat-normal:hover {
        transform: scale(1.1);
      }

      .seat-normal {
        background: #409EFF99;
        color: #FFFFFF;
        border: 2px solid #409EFF;
      }

      .seat-reserved {
        background: #E6A23C99;
        color: #FFFFFF;
        border: 2px solid #E6A23C;
        box-shadow: none;
      }

      .seat-using {
        background: #90939999;
        color: #FFFFFF;
        border: 2px solid #909399;
        box-shadow: none;
      }

      .seat-fault {
        background: #F56C6C99;
        color: #FFFFFF;
        border: 2px solid #F56C6C;
        box-shadow: none;
      }

      .seat-empty {
        border: 1px dashed #E9E9EB;
        box-shadow: none;
      }

      .seat-selected {
        background: #67C23A99;
        color: #FFFFFF;
        border: 2px solid #67C23A;
      }
    }
  }
}
</style>